# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
import re
import json
import paramiko
import jenkinsapi

from django.shortcuts import render
from django.http import HttpResponse
from .models import Testcases, Jenkins


# Common Variables
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SVN_DIR = '/root/testbed/SKS_product/Top/webTops'


def index(request):

    # 获取所有的Jenkins对象的主机地址
    jenkins_host = []
    jenkins = Jenkins.objects.all()
    for j in jenkins:
        jenkins_host.append(j.hostname)

    # 提取一个Jenkins对象中的所有jobs
    jobs = get_jobs_from_jenkins(jenkins[0].hostname)

    # 展示树结构中的第一个节点
    root = Testcases.objects.get(id=1)
    json_data = json.dumps({'id' : root.id, 'pId' : root.pId, 'name' : root.name, 'isParent' : True if root.isParent else False, 'fileUrl' : root.fileUrl})

    return render(request, 'index.html', {'json_data' : json_data, 'jobs' : json.dumps(jobs), 'jenkins' : json.dumps(jenkins_host)})



# 获取脚本文件内容
def show_case(request):

    caseId = request.GET.get('caseId')
    case = Testcases.objects.get(id = caseId)
    if case.fileUrl:
        with open(case.fileUrl, 'r') as f:
            content = f.read()

    return HttpResponse(content)



# 获取子节点用于展开数结构
def getChildNodes(request):

    pId = request.GET.get('pId')
    data = []
    nodes = Testcases.objects.filter(pId=pId).order_by('name')
    for node in nodes:
        data.append({'id':node.id, 'pId':node.pId, 'name':node.name, 'isParent':True if node.isParent else False, 'fileUrl':node.fileUrl})

    return HttpResponse(json.dumps(data))



# 获取被选中的节点(测试用例)并生成文件
def selectedNodes(request):

    cases = request.POST.get('selected_cases')
    jobName = request.POST.get('jobName')
    hostname = request.POST.get('jenkins')

    if cases:
        casesList = cases.split(";")
    caseNames = []
    for caseId in casesList:
        if caseId and caseId.isdigit():
            caseNames.append(Testcases.objects.get(id=int(caseId)).name)

    new_case_list = []
    for caseName in caseNames:
        if re.search('\d{4}\.txt', caseName):
            new_case_list.append(caseName)

    filename = jobName + '_variables.txt'
    with open(filename, 'w') as f:
        for caseName in new_case_list:
            f.write("-i " + caseName + "\n")

    result = copy_varaibles_to_dst(hostname, filename)

    with open(filename, 'r') as f:
        content = f.read()

    response = "<pre>" + content + '</pre><br/>'
    if result == 'OK':
        response += '<p></p>Upload file "%s" to Jenkins("%s") succeed!' % (filename, hostname)
    elif result == 'NOK':
        response += '<p></p>Upload file "%s" to Jenkins("%s") failed!' % (filename, hostname)        
    else:
        response += '<p></p>Upload Abnormal!!!' % filename 

    return HttpResponse(response)



# 获取Jenkins已有的Job
def get_jobs_from_jenkins(hostname):
    
    # 通过hostname查表获取对应的Jenkins对象
    jenkins_obj = Jenkins.objects.get(hostname = hostname)

    url = 'http://%s:8080' % jenkins_obj.hostname
    jobs = []
    J = jenkinsapi.jenkins.Jenkins(url, jenkins_obj.username, jenkins_obj.password)
    for job in J.get_jobs():
        jobs.append(job[0])

    return jobs     



# 获取Jenkins已有的Job并返回给前端
def get_jobs_from_jenkins_and_return(request):
    
    hostname = request.GET.get('hostname')

    # 通过hostname查表获取对应的Jenkins对象
    jenkins_obj = Jenkins.objects.get(hostname = hostname)

    url = 'http://%s:8080' % jenkins_obj.hostname
    jobs = ""
    J = jenkinsapi.jenkins.Jenkins(url, jenkins_obj.username, jenkins_obj.password)
    for job in J.get_jobs():
        # jobs.append(job[0]).append("&")
        jobs = jobs + job[0] + "&"

    return HttpResponse(jobs[:-1])



# 拷贝 variables 文件到指定的Job目录下
def copy_varaibles_to_dst(hostname, filename):

    dst_host = hostname
    dst_port = 22
    dst_user = 'root'
    dst_pass = '123.com'
    dst_path_1 = '/var/lib/jenkins/variables/'
    dst_path_2 = '/mnt/jenkins/variables/'

    try:
        t = paramiko.Transport((dst_host, dst_port))
        t.connect(username = dst_user, password = dst_pass)
        sftp = paramiko.SFTPClient.from_transport(t)
        try:
            sftp.put(os.path.join(BASE_DIR, filename), os.path.join(dst_path_1, filename))
        except IOError:
            sftp.put(os.path.join(BASE_DIR, filename), os.path.join(dst_path_2, filename))                        
        t.close()
    except Exception:
        return 'NOK'

    return 'OK'



# 遍历Top文件夹, 并且通过web页面展示
def select_top(request):
    
    top_files = search_top_files(SVN_DIR)
    return render(request, 'select_top.html' , {'tops' : top_files})


# 展示Top文件内容
def get_top_content(request):
    
    topfile = request.GET.get('topfile')
    if topfile:
        with open(os.path.join(SVN_DIR, topfile), 'r') as f:
            content = f.read()
        return HttpResponse(content)
    return HttpResponse()


# 保存对Top文件的修改
def save_selected_top(request):
    
    top = request.POST.get('top')
    return HttpResponse('Top -> ' + top)


# 保存对Top文件的修改
def save_modified_top(request):
    
    topfile = request.POST.get('topfile')
    content = request.POST.get('value')

    with open(os.path.join(SVN_DIR, topfile), 'w') as f:
        f.write(content)
    return HttpResponse(content)


def create_top(request):
    
    return render(request, 'create_top.html' , {})


def save_created_top(request):
    
    AC1_host = request.POST.get('AC1_host')  
    Cisco_host = request.POST.get('Cisco_host')
    POE_host = request.POST.get('POE_host')

    return HttpResponse(AC1_host + "\n" + Cisco_host + "\n" + POE_host)    




# 将新建或修改后的Top文件上传到SVN服务器
def save_file_to_svn(filename):

    filepath = os.path.join(SVN_DIR, filename)
    if os.path.isfile(filepath):
        os.popen('svn add %s' % filepath)
        os.popen('svn commit -m "updated by web" %s' % filepath)
    else:
        return 'file not exists!'


# 删除SVN服务器上指定的Top文件
def del_file_from_svn(filename):

    filepath = os.path.join(SVN_DIR, filename)
    if os.path.isfile(filepath):
        os.popen('svn delete %s' % filepath)
        os.popen('svn commit -m "updated by web" %s' % filepath)
    else:
        return 'file not exists!'


# 读取SVN目录下webTops文件
def search_top_files(dirpath):

    top_files = list()
    for parent, dirname, filenames in os.walk(dirpath):
        for filename in filenames:
            top_files.append(str(filename))

    print 'dirpath -> ', dirpath
    print 'top_files -> ', top_files
    return top_files
    